<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="商品名称" prop="prodName">
        <el-input
          v-model="queryParams.prodName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="SPU" prop="prodSpu">
        <el-input
          v-model="queryParams.prodSpu"
          placeholder="请输入SPU"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:product:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:product:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:product:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:product:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="productList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品ID" align="center" prop="prodId" />
      <el-table-column label="商品名称" align="center" prop="prodName">
        <template #default="scope">
          <span v-html="scope.row.prodName"></span>
        </template>
      </el-table-column>
      <el-table-column label="SPU" align="center" prop="prodSpu" />
      <el-table-column label="商品类型" align="center" prop="prodKind">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_prod_kind"
            :value="scope.row.prodKind"
          />
        </template>
      </el-table-column>
      <el-table-column label="商品分类" align="center" prop="typeName" />
      <el-table-column label="商品状态" align="center" prop="prodStatus">
        <template #default="scope">
          <span v-if="scope.row.prodStatus == 0">草稿</span>
          <span v-if="scope.row.prodStatus == 1">待审核</span>
          <span v-if="scope.row.prodStatus == 2">已上线</span>
          <span v-if="scope.row.prodStatus == 3">已下线</span>
          <span v-if="scope.row.prodStatus == 4">已缺货</span>
        </template>
      </el-table-column>

      <el-table-column label="商品品牌" align="center" prop="brandName" />
      <el-table-column label="商品单位" align="center" prop="unitId">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_prod_unit"
            :value="scope.row.unitId"
          />
        </template>
      </el-table-column>
      <el-table-column label="商品标签" align="center" prop="tagId">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_prod_tag"
            :value="scope.row.tagId"
          />
        </template>
      </el-table-column>
      <el-table-column label="供应商" align="center" prop="appr" />
      <el-table-column
        label="缩略图"
        align="center"
        prop="prodImage"
        width="100"
      >
        <template slot-scope="scope">
          <image-preview :src="scope.row.prodImage" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:product:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:product:remove']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-suitcase"
            @click="HandlerAddProdAtta(scope.row)"
            v-hasPermi="['product:atta:remove']"
            >商品附件
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-suitcase-1"
            @click="HandlerAddProdInfo(scope.row)"
            v-hasPermi="['product:info:remove']"
            >商品明细</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 商品添加 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="prodName">
          <el-input v-model="form.prodName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="SPU" prop="prodSpu">
          <el-input v-model="form.prodSpu" placeholder="请输入SPU" />
        </el-form-item>
        <el-form-item label="商品类型" prop="prodKind">
          <el-select
            v-model="form.prodKind"
            placeholder="请选择商品类型"
            clearable
          >
            <el-option
              v-for="dict in dict.type.sys_prod_kind"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品分类">
          <el-cascader
            v-model="form.prodType"
            :options="typeList"
            :show-all-levels="false"
            :props="calucatorProps"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="商品品牌">
          <el-select
            v-model="form.brandId"
            placeholder="请选择商品品牌"
            clearable
          >
            <el-option
              v-for="item in brandList"
              :key="item.brandId"
              :label="item.brandName"
              :value="item.brandId"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品单位" prop="unitId">
          <el-select
            v-model="form.unitId"
            placeholder="请选择商品单位 "
            clearable
          >
            <el-option
              v-for="dict in dict.type.sys_prod_unit"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品标签" prop="tagId">
          <el-select
            v-model="form.tagId"
            placeholder="请选择商品标签"
            clearable
          >
            <el-option
              v-for="dict in dict.type.sys_prod_tag"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="appr">
          <el-input v-model="form.appr" placeholder="请输入供应商" />
        </el-form-item>
        <el-form-item label="缩略图" prop="prodImage">
          <image-upload v-model="form.prodImage" :limit="1" />
        </el-form-item>
        <el-divider content-position="center">附件管理信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAddSysProdAtta"
              >添加</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDeleteSysProdAtta"
              >删除</el-button
            >
          </el-col>
        </el-row>
        <el-table
          :data="sysProdAttaList"
          :row-class-name="rowSysProdAttaIndex"
          @selection-change="handleSysProdAttaSelectionChange"
          ref="sysProdAtta"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="序号"
            align="center"
            prop="index"
            width="50"
          />
          <el-table-column label="商品视频" prop="attaVideo" width="200">
            <template slot-scope="scope">
              <file-upload
                v-model="scope.row.attaVideo"
                :file-type="['mp4', 'avi', 'mov', 'wmv']"
                :is-show-tip="false"
              />
            </template>
          </el-table-column>

          <el-table-column label="上架标示" prop="upFlag" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.upFlag" placeholder="选择上架标示">
                <el-option label="立即上架" :value="0" />
                <el-option label="定时上架" :value="1" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="定时上架时间" prop="upTime" width="240">
            <template slot-scope="scope">
              <el-date-picker
                clearable
                v-model="scope.row.upTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择定时上架时间"
              />
            </template>
          </el-table-column>
          <el-table-column label="定时下架标示" prop="downFlag" width="150">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.downFlag"
                placeholder="选择下架标示"
              >
                <el-option label="立即下架" :value="0" />
                <el-option label="定时下架" :value="1" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="定时下架时间" prop="downTime" width="240">
            <template slot-scope="scope">
              <el-date-picker
                clearable
                v-model="scope.row.downTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择定时下架时间"
              />
            </template>
          </el-table-column>
          <el-table-column label="轮播图片" prop="attaImages" width="200">
            <template slot-scope="scope">
              <image-upload
                v-model="scope.row.attaImages"
                :is-show-tip="false"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--商品附件 -->
    <el-dialog title="添加商品附件" :visible.sync="dialogFormVisible">
      <el-form
        ref="attaForm"
        :model="attaForm"
        :rules="attarules"
        label-width="80px"
      >
        <el-form-item label="商品视频" prop="attaVideo">
          <file-upload
            v-model="attaForm.attaVideo"
            :fileType="['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv']"
          />
        </el-form-item>

        <el-form-item label="上架" prop="upTime">
          <el-switch
            v-model="attaForm.upFlag"
            active-text="立即上架"
            inactive-text="定时上架"
            :active-value="0"
            :inactive-value="1"
          >
          </el-switch>
        </el-form-item>
        <el-form-item
          label="定时上架"
          prop="upTime"
          v-if="attaForm.upFlag == 1"
        >
          <el-date-picker
            clearable
            v-model="attaForm.upTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择定时上架时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="下架" prop="upTime">
          <el-switch
            v-model="attaForm.downFlag"
            active-text="立即下架"
            inactive-text="定时下架"
            :active-value="0"
            :inactive-value="1"
          >
          </el-switch>
        </el-form-item>
        <el-form-item
          label="定时下架"
          prop="downTime"
          v-if="attaForm.downFlag == 1"
        >
          <el-date-picker
            clearable
            v-model="attaForm.downTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择定时下架时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="轮播图片" prop="attaImages">
          <image-upload v-model="attaForm.attaImages" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAttaForm()">确定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 商品明细 -->

    <el-dialog title="添加商品明细" :visible.sync="InfoFormVisible">
      <el-form
        ref="infoForm"
        :model="infoForm"
        :rules="inforules"
        label-width="80px"
      >
        <el-form-item label="SKU" prop="prodSku">
          <el-input v-model="infoForm.prodSku" placeholder="请输入SKU" />
        </el-form-item>

        <el-form-item label="商品名称" prop="prodName">
          <el-input v-model="infoForm.prodName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品售价" prop="prodPrice">
          <el-input v-model="infoForm.prodPrice" placeholder="请输入商品售价" />
        </el-form-item>
        <el-form-item label="成本价" prop="costPrice">
          <el-input v-model="infoForm.costPrice" placeholder="请输入成本价" />
        </el-form-item>
        <el-form-item label="库存" prop="prodStock">
          <el-input v-model="infoForm.prodStock" placeholder="请输入库存" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitInfoForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProduct,
  listFormEs,
  getProduct,
  delProduct,
  addProduct,
  updateProduct,
} from "@/api/product/product";
import { addInfo } from "@/api/product/info";

import { addAtta } from "@/api/product/atta";
import { listType } from "@/api/product/type";
import FileUpload from "@/components/FileUpload";
import ImageUpload from "@/components/ImageUpload";
import { listBrand, listBrandAll } from "@/api/product/brand";
export default {
  name: "Product",
  components: {
    FileUpload,
    ImageUpload,
  },
  dicts: ["sys_prod_unit", "sys_prod_kind", "sys_prod_tag"],

  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSysProdAtta: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品列表表格数据
      productList: [],
      // 附件管理表格数据
      sysProdAttaList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dialogFormVisible: false,
      InfoFormVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 5,
        prodSpu: null,
        prodStatus: null,
        prodName: null,
      },
      // 表单参数
      form: {},
      attaForm: {},
      infoForm: {},
      // 表单校验
      rules: {
        prodSpu: [{ required: true, message: "SPU不能为空", trigger: "blur" }],
        prodKind: [
          { required: true, message: "商品类型不能为空", trigger: "change" },
        ],

        prodStatus: [
          { required: true, message: "商品状态不能为空", trigger: "change" },
        ],
        prodName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" },
        ],
        brandId: [
          { required: true, message: "商品品牌不能为空", trigger: "change" },
        ],
        unitId: [
          { required: true, message: "商品单位不能为空", trigger: "change" },
        ],
        tagId: [
          { required: true, message: "商品标签不能为空", trigger: "change" },
        ],
        appr: [{ required: true, message: "供应商不能为空", trigger: "blur" }],
        prodImage: [
          { required: true, message: "缩略图不能为空", trigger: "blur" },
        ],
      },
      attarules: {
        prodId: [
          { required: true, message: "商品ID不能为空", trigger: "change" },
        ],
        attaVideo: [
          { required: true, message: "商品视频不能为空", trigger: "blur" },
        ],
        upFlag: [
          { required: true, message: "上架标示不能为空", trigger: "change" },
        ],
        // upTime: [
        //   { required: true, message: "定时上架时间不能为空", trigger: "blur" },
        // ],
        downFlag: [
          {
            required: true,
            message: "定时下架标示不能为空",
            trigger: "change",
          },
        ],
        // downTime: [
        //   { required: true, message: "定时下架时间不能为空", trigger: "blur" },
        // ],
        attaImages: [
          { required: true, message: "轮播图片不能为空", trigger: "blur" },
        ],
      },
      inforules: {
        prodSku: [
          { required: true, message: "商品SKU不能为空", trigger: "blur" },
        ],
        prodName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" },
        ],
        prodPrice: [
          { required: true, message: "商品售价不能为空", trigger: "blur" },
        ],
        costPrice: [
          { required: true, message: "成本价不能为空", trigger: "blur" },
        ],
        prodStock: [
          { required: true, message: "库存不能为空", trigger: "blur" },
        ],
      },
      //商品分类
      typeList: [],
      calucatorProps: {
        label: "typeName",
        value: "typeId",
        children: "children",
        checkStrictly: true,
      },
      brandList: [],
    };
  },
  created() {
    this.getList();
    this.getTypeTree();
    this.getBrandList();
  },
  methods: {
    /** 查询品牌管理列表 */
    // getBrandList() {
    //   let params = {
    //     pageNum: 1,
    //     pageSize: 99999,
    //   };
    //   listBrand(params).then((response) => {
    //     this.brandList = response.rows;
    //     this.total = response.total;
    //   });
    // },
    getBrandList() {
      listBrandAll().then((response) => {
        if (response.code == 200) {
          this.brandList = response.data;
        }
      });
    },
    /** 查询商品分类列表 */
    getTypeTree() {
      let params = {
        pageNum: 1,
        pageSize: 99999,
      };
      listType(params).then((response) => {
        this.typeList = this.handleTree(response.data, "typeId", "typePid");
      });
    },
    /** 查询商品列表列表 */
    getList() {
      this.loading = true;
      listFormEs(this.queryParams).then((response) => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.dialogFormVisible = false;
      this.InfoFormVisible = false;
      this.open = false;
      this.reset();
      this.resetAtta();
      this.restInfo();
    },
    // 表单重置
    reset() {
      this.form = {
        prodId: null,
        prodSpu: null,
        prodKind: null,
        prodType: null,
        prodStatus: null,
        prodName: null,
        brandId: null,
        unitId: null,
        tagId: null,
        appr: null,
        prodImage: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.sysProdAttaList = [];
      this.resetForm("form");
    },
    // 表单重置
    resetAtta() {
      this.attaForm = {
        attaId: null,
        prodId: null,
        attaVideo: null,
        upFlag: null,
        upTime: null,
        downFlag: null,
        downTime: null,
        attaImages: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("attaForm");
    },
    restInfo() {
      this.infoForm = {
        infoId: null,
        prodSku: null,
        prodId: null,
        prodName: null,
        prodPrice: null,
        costPrice: null,
        prodStock: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("infoForm");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.prodId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /**新增商品附件按钮 */
    HandlerAddProdAtta(row) {
      this.resetAtta();
      this.attaForm.prodId = row.prodId;
      this.dialogFormVisible = true;
    },
    /**新增商品明细按钮 */
    HandlerAddProdInfo(row) {
      this.restInfo();
      this.infoForm.prodId = row.prodId;
      this.InfoFormVisible = true;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品列表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const prodId = row.prodId || this.ids;
      getProduct(prodId).then((response) => {
        this.form = response.data;
        this.sysProdAttaList = response.data.sysProdAttaList;
        this.open = true;
        this.title = "修改商品列表";
      });
    },
    /**附件提交按钮 */
    submitAttaForm() {
      this.$refs["attaForm"].validate((valid) => {
        if (valid) {
          addAtta(this.attaForm).then((response) => {
            this.$modal.msgSuccess("新增成功");
            this.dialogFormVisible = false;
            this.$router.push("/product/atta");
          });
        }
      });
    },
    /**明细提交按钮 */
    submitInfoForm() {
      this.$refs["infoForm"].validate((valid) => {
        if (valid) {
          addInfo(this.infoForm).then((response) => {
            this.$modal.msgSuccess("新增成功");
            this.InfoFormVisible = false;
            this.$router.push("/product/info");
          });
        }
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.prodType.length > 0) {
            this.form.prodType =
              this.form.prodType[this.form.prodType.length - 1];
          }
          this.form.sysProdAttaList = this.sysProdAttaList;
          if (this.form.prodId != null) {
            updateProduct(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const prodIds = row.prodId || this.ids;
      this.$modal
        .confirm('是否确认删除商品列表编号为"' + prodIds + '"的数据项？')
        .then(function () {
          return delProduct(prodIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 附件管理序号 */
    rowSysProdAttaIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 附件管理添加按钮操作 */
    handleAddSysProdAtta() {
      let obj = {};
      obj.attaVideo = "";
      obj.upFlag = "";
      obj.upTime = "";
      obj.downFlag = "";
      obj.downTime = "";
      obj.attaImages = "";
      obj.createBy = "";
      obj.createTime = "";
      obj.updateBy = "";
      obj.updateTime = "";
      this.sysProdAttaList.push(obj);
    },
    /** 附件管理删除按钮操作 */
    handleDeleteSysProdAtta() {
      if (this.checkedSysProdAtta.length == 0) {
        this.$modal.msgError("请先选择要删除的附件管理数据");
      } else {
        const sysProdAttaList = this.sysProdAttaList;
        const checkedSysProdAtta = this.checkedSysProdAtta;
        this.sysProdAttaList = sysProdAttaList.filter(function (item) {
          return checkedSysProdAtta.indexOf(item.index) == -1;
        });
      }
    },
    /** 复选框选中数据 */
    handleSysProdAttaSelectionChange(selection) {
      this.checkedSysProdAtta = selection.map((item) => item.index);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "product/product/export",
        {
          ...this.queryParams,
        },
        `product_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
